package map.android.baidu.carpool.page.home;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.lbs.place.user.UserCenter;
import com.baidu.mapframework.api.NewSearchCallback;
import com.baidu.mapframework.api.SearchResponce;
import com.baidu.mapframework.component.comcore.exception.ComException;
import com.baidu.mapframework.component.comcore.impl.message.DefaultComRequestFactory;
import com.baidu.mapframework.component.comcore.impl.message.params.ComBaseParams;
import com.baidu.mapframework.component.comcore.manager.ComponentManager;
import com.baidu.mapframework.component.comcore.message.ComRequest;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.baidu.platform.comapi.map.MapUtils;
import com.baidu.sapi2.callback.SapiCallback;
import com.baidu.sapi2.result.DynamicPwdLoginResult;
import map.android.baidu.carpool.Config;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.AccountData;
import map.android.baidu.carpool.data.impl.HomePageBaseInfoData;
import map.android.baidu.carpool.data.impl.MainConfigData;
import map.android.baidu.carpool.data.impl.OrderCreateData;
import map.android.baidu.carpool.model.CarPoolType;
import map.android.baidu.carpool.model.CarpoolPosition;
import map.android.baidu.carpool.model.LocalePlaceInfo;
import map.android.baidu.carpool.model.URLModel;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.usercenter.UserCenterPage;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.reservation.CarDateTimeDialog;
import map.android.baidu.carpool.reservation.CarDateTimeDialog.OnSelectDateTimeListener;
import map.android.baidu.carpool.reservation.CarDateTimeDialog.OnSelectNowListener;
import map.android.baidu.carpool.response.AccountResponse;
import map.android.baidu.carpool.response.HomePageBaseInfoResponse;
import map.android.baidu.carpool.response.MainConfigResponse;
import map.android.baidu.carpool.response.OrderCreateResponse;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.CarPoolReceiptDialog;
import map.android.baidu.carpool.utils.CarUserLoginDialog;
import map.android.baidu.carpool.utils.CountDownTimerUtil;
import map.android.baidu.carpool.utils.InstructionsForUserDialog;
import map.android.baidu.carpool.utils.StatisticsUtil;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.utils.ToastForCarpool;
import map.android.baidu.carpool.utils.UniversalSourceFromParameter;
import map.android.baidu.carpool.widget.TextinputHistroyAndSugListView;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by zhaoyangyang on 2015/3/22.
 */
public class CarpoolHomePage extends CarpoolBasePage implements View.OnClickListener, OnSelectNowListener,
        OnSelectDateTimeListener, InstructionsForUserDialog.CallBack {
    private View mView = null;
    private View mTimeLin = null;
    private Calendar mCalendarSelected = null;
    private TextView mStartNowText = null;
    private LinearLayout mOneLayerLin = null;
    private TextView mAppointmentLin = null;
    private CarpoolPosition mStartPosition = null;
    private CarpoolPosition mEndPosition = null;
    private CarpoolPosition mTempStartPosition = null;
    private TextView mTextStartName = null;
    private TextView mTextEndName = null;
    private ArrayList<CarPoolType> carTypeList = new ArrayList<CarPoolType>();
    private List<View> mList = new ArrayList<View>();
    private TitleHelpler mTitleHelper;
    private View mHorizontalScrollView;
    private LinearLayout mLayoutCarType;
    private TextView taixPirce;

    private TextView mOrderStatusTV = null;
    private RelativeLayout mRemindRLTV = null;

    private ArrayList<CarPoolType> carOnclickList = new ArrayList<CarPoolType>();
    private ArrayList<CarPoolType> carOnclickListClone = null;

    //private CarPoolReceiptDialog mReceiptDialog;
    private InstructionsForUserDialog mInstructionsForUserDialog;

    //y:39.856387326682025 纬度 latitude
    //x:116.31421660437348  经度 longitude

    private CarpoolPosition mLastStartPosition = null;
    private CarpoolPosition mLastEndPosition = null;
    /**
     * 个人中心
     */
    private boolean mFromPersonLogin = false;
    private int dateLimit = 3;
    private boolean isloading = false;
    private TextView mRefreshText = null;
    private ProgressBar mProgressLoading = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            mLastStartPosition = CarpoolSharedPreferences.getLatestStartPlaceInfo(mActivity);
            mLastEndPosition = CarpoolSharedPreferences.getLatesEndPlaceInfo(mActivity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StatisticsUtil.getInstance().addStatisticsOnline(
                StatisticsUtil.DA_SRC_VALUE_MAIN_PAGE + "." + UniversalSourceFromParameter.getInstance().getSrcFrom());
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                requestPrice();
            }

        }
    };

    /**
     * 根据基线初始化家和公司
     */
    private void initHomeAndCompanyByTrans() {

        CarpoolPosition homePlaceInfo = CarpoolSharedPreferences.getHomeGeoAddrInfo(APIProxy.res().getBaseActivity());
        CarpoolPosition companyPlaceInfo =
                CarpoolSharedPreferences.getCompanyGeoAddrInfo(APIProxy.res().getBaseActivity());
        final String startAdd = homePlaceInfo.address;
        final String endAdd = companyPlaceInfo.address;

        if (homePlaceInfo != null && !"".equals(homePlaceInfo.address) && homePlaceInfo.x != 0.0 && homePlaceInfo.y != 0.0) {
            //存在家
            mStartPosition = (CarpoolPosition) homePlaceInfo.clone();
            APIProxy.newSearch().reverseGeoCode((int) homePlaceInfo.x, (int) homePlaceInfo.y,
                    new NewSearchCallback() {
                        @Override
                        public void onSuccessResponce(SearchResponce responce) {
                            try {
                                if (responce.resultType == SearchResponce.JSON_RESULT) {
                                    JSONObject jsonObject = new JSONObject(responce.json);
                                    JSONArray poiArray = jsonObject.optJSONArray("surround_poi");
                                    if (poiArray != null && poiArray.get(0) != null) {
                                        JSONObject object = (JSONObject) poiArray.get(0);
                                        if (TextUtils.isEmpty(mTextStartName.getText())) {
                                            String name = object.optString("name");
                                            if (object.optInt("distance") > 15) {
                                                if (!TextUtils.isEmpty(startAdd)) {
                                                    mStartPosition.name = startAdd;
                                                } else {
                                                    mStartPosition.name = "在" + name + "附近";
                                                }
                                            } else {
                                                mStartPosition.name = name;
                                            }
                                            mTextStartName.setText(mStartPosition.name);
                                            handler.removeMessages(1);
                                            handler.sendEmptyMessage(1);
                                        }

                                    } else {
                                        if (TextUtils.isEmpty(mTextStartName.getText())) {
                                            mStartPosition.name = jsonObject.optString("address");
                                            mTextStartName.setText(jsonObject.optString("address"));
                                            handler.removeMessages(1);
                                            handler.sendEmptyMessage(1);
                                        }
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onErrorResponce(SearchResponce responce) {
                        }
                    });

        }

        if (companyPlaceInfo != null && !"".equals(companyPlaceInfo.address) && companyPlaceInfo.x != 0.0 && companyPlaceInfo.y != 0.0) {
            //存在公司
            mEndPosition = (CarpoolPosition) companyPlaceInfo.clone();
            APIProxy.newSearch().reverseGeoCode((int) companyPlaceInfo.x, (int) companyPlaceInfo.y,
                    new NewSearchCallback() {
                        @Override
                        public void onSuccessResponce(SearchResponce responce) {
                            try {
                                if (responce.resultType == SearchResponce.JSON_RESULT) {
                                    JSONObject jsonObject = new JSONObject(responce.json);
                                    JSONArray poiArray = jsonObject.optJSONArray("surround_poi");
                                    if (poiArray != null && poiArray.get(0) != null) {
                                        JSONObject object = (JSONObject) poiArray.get(0);
                                        if (TextUtils.isEmpty(mTextEndName.getText())) {
                                            String name = object.optString("name");
                                            if (object.optInt("distance") > 15) {
                                                if (!TextUtils.isEmpty(endAdd)) {
                                                    mEndPosition.name = endAdd;
                                                } else {
                                                    mEndPosition.name = "在" + name + "附近";
                                                }
                                            } else {
                                                mEndPosition.name = name;
                                            }
                                            mTextEndName.setText(mEndPosition.name);
                                            handler.removeMessages(1);
                                            handler.sendEmptyMessage(1);
                                        }

                                    } else {
                                        if (TextUtils.isEmpty(mTextEndName.getText())) {
                                            mEndPosition.name = jsonObject.optString("address");
                                            mTextEndName.setText(jsonObject.optString("address"));
                                            handler.removeMessages(1);
                                            handler.sendEmptyMessage(1);
                                        }

                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onErrorResponce(SearchResponce responce) {
                        }
                    });

        }

    }

    private void initStartAndEnd() {
        try {
            if (hasLastStartAndEndPositionMsg()) {
                initHomeAndCompanyByHistory();
            } else {
                initHomeAndCompanyByTrans();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = APIProxy.res().inflate(R.layout.layout_home_page);
            initView();
            initData();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
            //initStartAndEnd();
        }
        if (!isNavigateBack()){
            initStartAndEnd();
        }
        return mView;
    }

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isNavigateBack()) {
            if(getBackwardArguments() !=null && getBackwardArguments().containsKey(TextInputSugPage.KEY_PARAM_TYPE)){
                handleBackwardArguments(getBackwardArguments());
                setStartPointAndEndPointText();
            }

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserInfoSetting.isLogin()) {
            requestBaseInfo();
        }
    }

    private void initView() {
        // mReceiptDialog = new CarPoolReceiptDialog(mActivity);
        mOneLayerLin = (LinearLayout) mView.findViewById(R.id.lin_one_layer);
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(this);
        mTitleHelper.setCenterView("百度顺风车");
        mTitleHelper.setRightView(this);

        mTimeLin = mOneLayerLin.findViewById(R.id.lin_time);
        mStartNowText = (TextView) mOneLayerLin.findViewById(R.id.btn_time);
        mAppointmentLin = (TextView) mView.findViewById(R.id.appointment_lin);
        mTextStartName = (TextView) mView.findViewById(R.id.tv_start);
        mTextEndName = (TextView) mView.findViewById(R.id.tv_to);
        mView.findViewById(R.id.plug_input_lin).findViewById(R.id.iv_exchange).setOnClickListener(this);
        mHorizontalScrollView = mView.findViewById(R.id.car_costimate_scrollview);
        mLayoutCarType = (LinearLayout) mView.findViewById(R.id.car_layout_car_type);
        taixPirce = (TextView) mView.findViewById(R.id.tv_price);
        mRefreshText = (TextView) mView.findViewById(R.id.tv_refresh);
        mRefreshText.setOnClickListener(this);
        mRefreshText.setVisibility(View.GONE);
        mProgressLoading = (ProgressBar) mView.findViewById(R.id.progress_loading);
        mProgressLoading.setVisibility(View.GONE);

        mRemindRLTV = (RelativeLayout) mView.findViewById(R.id.rltv_order_remind);
        mOrderStatusTV = (TextView) mView.findViewById(R.id.tv_home_order_status);

        mAppointmentLin.setOnClickListener(this);
        mTextStartName.setOnClickListener(this);
        mTextEndName.setOnClickListener(this);
        mTimeLin.setOnClickListener(this);
        taixPirce.setVisibility(View.GONE);
        mView.findViewById(R.id.carejion).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_JOIN_DRIVER_TEAM, "");
                if (!checkNetworkStatus(true)) {
                    return;
                }
                if (Config.MONKEY_OPEN) {
                    return;
                }
                UserInfoSetting.goToWebShell(URLModel.CARE_JOIN_URL, "车主加盟");
            }
        });
        mView.findViewById(R.id.price_detai).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!checkNetworkStatus(true)) {
                    return;
                }
                UserInfoSetting.goToWebShell(URLModel.PRICRE_LIST_URL, "车型费用");

            }
        });
        setTimeText(mCalendarSelected);

        mInstructionsForUserDialog =
                new InstructionsForUserDialog(getActivity(), this);

    }

    /**
     * 车型容器
     */
    private void addHorizontalScrollViewChild(boolean hasShowPrice) {
        mLayoutCarType.removeAllViews();
        addChild(hasShowPrice);
    }

    /**
     * 添加车型子View
     */
    private void addChild(boolean hasShowPrice) {
        if (carTypeList.size() <= 0) {
            return;
        }
        carOnclickList.clear();
        carOnclickList.addAll(this.carTypeList);
        carOnclickListClone = (ArrayList<CarPoolType>) carOnclickList.clone();
        if (TextUtils.isEmpty(mTextStartName.getText())) {
            carOnclickList.clear();
        }

        int margin = APIProxy.res().getResources().getDimensionPixelOffset(R.dimen.d_14) - 2;
        int size = carTypeList.size();
        for (int i = 0; i < size; i++) {
            final int pos = i;
            final View child = APIProxy.res().inflate(R.layout.right_car_type_new);
            LinearLayout.LayoutParams params = new LayoutParams((APIProxy.sys().getScreenWidth() - margin) / 3, -2);
            child.setLayoutParams(params);
            child.setTag(i);
            mLayoutCarType.addView(child);
            final ImageView imgTv = (ImageView) child.findViewById(R.id.iv_choose_type);
            final View line = child.findViewById(R.id.carpool_cartype_line);

            final TextView carTypeTv = (TextView) child.findViewById(R.id.tv_price_type);
            final TextView carNameTv = (TextView) child.findViewById(R.id.tv_car_type);
            final TextView carPrice = (TextView) child.findViewById(R.id.tv_price_1);
            if (mTextStartName.getText().length() > 0 && mTextEndName.getText().length() > 0) {
                imgTv.setTag(null);
                imgTv.setImageResource(R.drawable.home_xuanzhong);
                carPrice.setTextColor(APIProxy.res().getResources().getColor(R.color.price_color));
                carTypeTv.setTextColor(APIProxy.res().getResources().getColor(R.color.car_type_on));
                child.setEnabled(true);
            } else {
                imgTv.setImageResource(R.drawable.home_weixuanzhong);
                carPrice.setTextColor(APIProxy.res().getResources().getColor(R.color.pay_time_out_gray));
                carTypeTv.setTextColor(APIProxy.res().getResources().getColor(R.color.car_type_off));
                imgTv.setTag("tag");
                child.setEnabled(false);

            }
            carTypeTv.setText(carTypeList.get(i).name);
            carNameTv.setText(carTypeList.get(i).desc);
            if (hasShowPrice) {
                carPrice.setVisibility(View.VISIBLE);
                carPrice.setText("¥ " + carTypeList.get(i).fee);
            } else {
                carPrice.setVisibility(View.INVISIBLE);
            }

            child.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (imgTv.getTag() == null) {
                        if (carOnclickList.size() > 1) {
                            imgTv.setTag("tag");
                            imgTv.setImageResource(R.drawable.home_weixuanzhong);
                            carPrice.setTextColor(APIProxy.res().getResources().getColor(R.color.pay_time_out_gray));
                            carTypeTv.setTextColor(APIProxy.res().getResources().getColor(R.color.car_type_off));
                            carOnclickList.remove(carOnclickListClone.get(pos));
                        } else {
                            ToastForCarpool.show(mActivity, "至少选择一种车型");
                        }

                    } else {
                        imgTv.setTag(null);
                        imgTv.setImageResource(R.drawable.home_xuanzhong);
                        carPrice.setTextColor(APIProxy.res().getResources().getColor(R.color.price_color));
                        carTypeTv.setTextColor(APIProxy.res().getResources().getColor(R.color.car_type_on));
                        carOnclickList.add(carOnclickListClone.get(pos));
                    }
                }
            });

            if (i == size - 1) {
                line.setVisibility(View.GONE);
            }

        }
    }

    private void initData() {
        if (mStartPosition == null) {
            mStartPosition = new CarpoolPosition();
        }
        if (mEndPosition == null) {
            mEndPosition = new CarpoolPosition();
        }
        if (mTempStartPosition == null) {
            mTempStartPosition = new CarpoolPosition();
        }
        if (!checkNetworkStatus(true)) {
            ToastForCarpool.show(mActivity, "网络异常");
            return;
        }
        initStartPosition();
        // showLoadingDialog(true);
        requestConfig();
        // initStartAndEnd();
    }

    private void initHomeAndCompanyByHistory() {
        mStartPosition = mLastStartPosition;
        mEndPosition = mLastEndPosition;
        setStartPointAndEndPointText();

    }

    private boolean hasLastStartAndEndPositionMsg() {
        if (mLastStartPosition == null || mLastEndPosition == null) {
            return false;
        }
        return true;
    }

    private void requestBaseInfo() {

        final HomePageBaseInfoData homePageBaseInfoData = new HomePageBaseInfoData(mActivity);
        homePageBaseInfoData.setBduss(UserInfoSetting.getBduss());
        homePageBaseInfoData.post(new IDataStatusChangedListener<HomePageBaseInfoResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<HomePageBaseInfoResponse> comNetData,
                                            HomePageBaseInfoResponse homePageBaseInfoResponse, int i) {
                //TODO 如果登陆去请求最新订单状态信息

                if (homePageBaseInfoResponse != null && homePageBaseInfoResponse.data != null) {
                    if (homePageBaseInfoResponse.data.orderInfo != null) {
                        //TODO 有最近一单消息
                        mRemindRLTV.setVisibility(View.VISIBLE);
                        mTitleHelper.setRightViewImageResource(R.drawable.person_center_point);
                        mOrderStatusTV.setText(homePageBaseInfoResponse.data.orderInfo.orderStatusDesc);
                        final String orderId = homePageBaseInfoResponse.data.orderInfo.order_id;
                        final int status = homePageBaseInfoResponse.data.orderInfo.status;
                        mRemindRLTV.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //TODO 订单列表
                                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_MAIN_PAGE,
                                        StatisticsUtil.OFFLINE_ACT_CHECK_ORDER_BT);
                                if (status == 2) {
                                    showReceiptDialog(orderId, 0);
                                } else {
                                    Bundle b = new Bundle();
                                    b.putString("orderId", orderId);
                                    APIProxy.navi().navigateTo(OrderDetailPage.class, b);
                                }

                            }
                        });
                        //TODO 显示状态倒计时10s
                        CountDownTimerUtil countDownTimerUtil = new CountDownTimerUtil(10000L);
                        countDownTimerUtil.setDownTimeListener(new CountDownTimerUtil.CompleteDownTime() {
                            @Override
                            public void downTimeComplete() {
                                try {
                                    mRemindRLTV.setVisibility(View.GONE);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                        countDownTimerUtil.startDownTime();
                    } else {
                        //TODO 用户从未下单，或因为异常没有最近一单的消息
                        mRemindRLTV.setVisibility(View.GONE);
                        mTitleHelper.setRightViewImageResource(R.drawable.home_geren);
                    }

                } else {
                    ToastForCarpool.show(mActivity, "网络异常，请稍候再试");
                }

            }
        });

    }

    /**
     * 请求config接口
     */
    private void requestConfig() {
        mProgressLoading.setVisibility(View.VISIBLE);
        mRefreshText.setVisibility(View.GONE);
        MainConfigData mainConfigData = new MainConfigData(mActivity);
        mainConfigData.setCityCode(UserInfoSetting.getCityId());
        if (CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity()) != null
                && CarpoolSharedPreferences
                .getCacheMainConfigResponse(APIProxy.res().getBaseActivity()).data != null && CarpoolSharedPreferences
                .getCacheMainConfigResponse(APIProxy.res().getBaseActivity()).data.carType != null) {

            mainConfigData.setCache(CarpoolSharedPreferences
                    .getCacheMainConfigResponse(APIProxy.res().getBaseActivity()).data.cache);

        }

        mainConfigData.get(new IDataStatusChangedListener<MainConfigResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<MainConfigResponse> comNetData,
                                            MainConfigResponse mainConfigResponse,
                                            int i) {
                carTypeList.clear();
                /**
                 * 为组件入口保存配置信息
                 */
                if (mainConfigResponse != null && mainConfigResponse.data != null && mainConfigResponse.getErrorNo()
                        == 0) {

                    if (CarpoolSharedPreferences.getCacheMainConfigResponse(mActivity) !=
                            null && CarpoolSharedPreferences.getCacheMainConfigResponse(mActivity).data != null) {

                        if (CarpoolSharedPreferences.getCacheMainConfigResponse(mActivity).data.cache.equals
                                (mainConfigResponse.data.cache)) {
                            mainConfigResponse = CarpoolSharedPreferences.getCacheMainConfigResponse(mActivity);
                        } else {
                            CarpoolSharedPreferences.setCacheMainConfigResponse(mActivity, mainConfigResponse);
                        }

                    }

                    dateLimit = mainConfigResponse.data.dateLimit;
                    if (mainConfigResponse.data.carType != null) {
                        for (int k = 0; k < mainConfigResponse.data.carType.size(); k++) {
                            CarPoolType carPoolType = new CarPoolType();
                            carPoolType.name = mainConfigResponse.data.carType.get(k).name;
                            carPoolType.desc = mainConfigResponse.data.carType.get(k).desc;
                            carPoolType.type = mainConfigResponse.data.carType.get(k).type;
                            carPoolType.fee = null;
                            carTypeList.add(carPoolType);
                        }
                        mHorizontalScrollView.setVisibility(View.VISIBLE);
                        addHorizontalScrollViewChild(false);
                    }

                } else {
                    ToastForCarpool.show(mActivity, "网络异常，请检查网络");
                    mHorizontalScrollView.setVisibility(View.GONE);
                    mRefreshText.setVisibility(View.VISIBLE);
                }
                mProgressLoading.setVisibility(View.GONE);
                //showLoadingDialog(false);
            }
        });
    }

    @Override
    public void dateTimeSelected(Calendar c) {
        setTimeText(c);
    }

    @Override
    public void selectNow() {
        setTimeText(null);
    }

    private void setTimeText(Calendar c) {
        mCalendarSelected = c;

        if (mCalendarSelected == null) {
            mCalendarSelected = Calendar.getInstance(Locale.CHINESE);
            mCalendarSelected.add(mCalendarSelected.MINUTE, 30);
            mCalendarSelected.setTimeInMillis(mCalendarSelected.getTimeInMillis() + (10 * 60 * 1000 - mCalendarSelected
                    .getTimeInMillis() %
                    (10 * 60 * 1000)));
            if (mCalendarSelected.get(Calendar.HOUR_OF_DAY) < 6) {
                mCalendarSelected.set(Calendar.HOUR_OF_DAY, 6);
                mCalendarSelected.set(Calendar.MINUTE, 0);
                mCalendarSelected.set(Calendar.MILLISECOND, 0);

            }

            if (mCalendarSelected.get(Calendar.HOUR_OF_DAY) > 22) {
                mCalendarSelected.add(Calendar.DAY_OF_MONTH, 1);
                mCalendarSelected.set(Calendar.HOUR_OF_DAY, 6);
                mCalendarSelected.set(Calendar.MINUTE, 0);
                mCalendarSelected.set(Calendar.MILLISECOND, 0);

            }
            SimpleDateFormat f = new SimpleDateFormat("MM月dd日 E HH:mm");
            mStartNowText.setText(f.format(mCalendarSelected.getTime()));
        } else {
            Date date = mCalendarSelected.getTime();
            SimpleDateFormat f = new SimpleDateFormat("MM月dd日 E HH:mm");
            String s = f.format(date);
            mStartNowText.setText(s);
        }
        // requestPrice();
    }

    @Override
    public boolean onBackPressed() {
        if (Config.MONKEY_OPEN) {
            return true;
        }
        return super.onBackPressed();
    }

    private void setStartPointAndEndPointText() {
        if (mEndPosition != null && !TextUtils.isEmpty(mEndPosition.name) && mTextEndName != null) {
            if (mEndPosition.name.equals("我的位置")) {
                reverseGeoCode(mEndPosition, mTempStartPosition, mTextEndName);
            } else {
                mTextEndName.setText(mEndPosition.name);
            }
        } else {
            if (mTextEndName != null) {
                mTextEndName.setText(null);
            }
        }
        if (mStartPosition != null && !TextUtils.isEmpty(mStartPosition.name) && mTextStartName != null) {
            if (mStartPosition.name.equals("我的位置")) {
                reverseGeoCode(mStartPosition, mTempStartPosition, mTextStartName);
            } else {
                mTextStartName.setText(mStartPosition.name);
            }
        } else {
            if (mTextStartName != null) {
                mTextStartName.setText(null);
            }
        }
        if (!TextUtils.isEmpty(mTextStartName.getText()) && !TextUtils.isEmpty(mTextEndName.getText())) {
            requestPrice();
        }
    }

    /**
     * 请求Account接口的数据
     */
    private void requestPrice() {
        mProgressLoading.setVisibility(View.VISIBLE);
        mRefreshText.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(mTextStartName.getText()) && mStartPosition != null && !TextUtils.isEmpty(mTextEndName
                .getText()) && mEndPosition != null && mCalendarSelected != null) {

            final AccountData accountData = new AccountData(mActivity);
            GeoPoint start = new GeoPoint(mStartPosition.y, mStartPosition.x);
            GeoPoint end = new GeoPoint(mEndPosition.y, mEndPosition.x);

            accountData.setStartGeo(MapUtils.mc2ll(start));
            accountData.setEndGeo(MapUtils.mc2ll(end));

            accountData.setTime((mCalendarSelected.getTime().getTime()) + "");
            accountData.get(new IDataStatusChangedListener<AccountResponse>() {
                @Override
                public void onDataStatusChanged(ComNetData<AccountResponse> comNetData, AccountResponse accountResponse,
                                                int i) {
                    if (accountResponse != null && accountResponse.data != null) {
                        carTypeList.clear();
                        if (accountResponse.getErrorNo() == -6) {
                            taixPirce.setVisibility(View.GONE);
                            mHorizontalScrollView.setVisibility(View.GONE);
                            ToastForCarpool.show(mActivity, "有点远，车主暂时不能接单!");
                            mAppointmentLin.setEnabled(false);
                            return;
                        } else {
                            mAppointmentLin.setEnabled(true);
                        }
                        taixPirce.setVisibility(View.VISIBLE);
                        taixPirce.setText("同等距离出租车约" + accountResponse.data.distance.total_price + "元");
                        for (int k = 0; k < accountResponse.data.fee.size(); k++) {
                            CarPoolType carPoolType = new CarPoolType();
                            carPoolType.name = accountResponse.data.fee.get(k).name;
                            carPoolType.desc = accountResponse.data.fee.get(k).desc;
                            carPoolType.type = accountResponse.data.fee.get(k).type;
                            carPoolType.fee = accountResponse.data.fee.get(k).fee;
                            carTypeList.add(carPoolType);
                        }

                        mHorizontalScrollView.setVisibility(View.VISIBLE);
                        addHorizontalScrollViewChild(true);
                    } else {
                        taixPirce.setVisibility(View.GONE);
                        mHorizontalScrollView.setVisibility(View.GONE);
                        mRefreshText.setVisibility(View.VISIBLE);
                        ToastForCarpool.show(mActivity, "网络异常,请稍候再试");
                    }
                    mProgressLoading.setVisibility(View.GONE);
                }
            });

        } else {
            mProgressLoading.setVisibility(View.GONE);
            taixPirce.setVisibility(View.GONE);
            mHorizontalScrollView.setVisibility(View.GONE);
            mRefreshText.setVisibility(View.GONE);
            // ToastForCarpool.show(mActivity,"出发地或目的地为空");
        }
    }

    private void initStartPosition() {
        mTempStartPosition.x = UserInfoSetting.getBaiduMocLng();
        mTempStartPosition.y = UserInfoSetting.getBaiduMocLat();
        if (mTempStartPosition.x <= 0 && mTempStartPosition.y <= 0) {
            return;
        }
        APIProxy.newSearch().reverseGeoCode((int) mTempStartPosition.x, (int) mTempStartPosition.y,
                new NewSearchCallback() {
                    @Override
                    public void onSuccessResponce(SearchResponce responce) {
                        try {
                            if (responce.resultType == SearchResponce.JSON_RESULT) {
                                String jsonString = responce.json;
                                JSONObject jsonObject = new JSONObject(jsonString);
                                mTempStartPosition.address = jsonObject.optString("address");
                                JSONArray poiArray = jsonObject.optJSONArray("surround_poi");
                                if (poiArray != null && poiArray.get(0) != null) {
                                    JSONObject object = (JSONObject) poiArray.get(0);
                                    mTempStartPosition.name = object.optString("name");
                                } else {
                                    mTempStartPosition.name = mTempStartPosition.address;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onErrorResponce(SearchResponce responce) {
                        try {
                            if (mStartPosition != null && !TextUtils.isEmpty(mStartPosition.address)
                                    && !TextUtils.isEmpty(mStartPosition.name)) {
                                mStartPosition.address = "我的位置";
                                mStartPosition.name = "我的位置";
                                setStartPointAndEndPointText();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 当起始位置传来是“我的位置”四个字时，需要反geo出具体的地点
     */
    private void reverseGeoCode(final CarpoolPosition position, final CarpoolPosition mTempStartPosition,
                                final TextView tv) {
        APIProxy.newSearch().reverseGeoCode((int) mTempStartPosition.x, (int) mTempStartPosition.y,
                new NewSearchCallback() {
                    @Override
                    public void onSuccessResponce(SearchResponce responce) {
                        try {
                            if (responce.resultType == SearchResponce.JSON_RESULT) {
                                JSONObject jsonObject = new JSONObject(responce.json);
                                JSONArray poiArray = jsonObject.optJSONArray("surround_poi");
                                if (poiArray != null && poiArray.get(0) != null) {
                                    JSONObject object = (JSONObject) poiArray.get(0);
                                    position.name = object.optString("name");
                                    tv.setText(object.optString("name"));
                                } else {
                                    position.name = jsonObject.optString("address");
                                    tv.setText(jsonObject.optString("address"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onErrorResponce(SearchResponce responce) {
                    }
                });
    }

    private boolean isFirst() {
        Boolean isFirstLogin = true;
        SharedPreferences sp = mActivity.getSharedPreferences("first", getActivity().MODE_PRIVATE);
        isFirstLogin = sp.getBoolean("isFirst", true);
        return isFirstLogin;
    }

    private void showLoginDialog(int res) {
        StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_LOGIN_PAGE, "");
        final CarUserLoginDialog loginDialog = new CarUserLoginDialog(getActivity(), res);
        CarUserLoginDialog.CallBack okListener = new CarUserLoginDialog.CallBack() {

            @Override
            public void onClick(View v, String phone, String code) {
                showLoadingDialog(true);
                userLogin(v, phone, code);
            }
        };
        loginDialog.showDialog(loginDialog, okListener);
    }

    private void userLogin(final View v, String phone, String code) {
        SapiCallback<DynamicPwdLoginResult> callback = new SapiCallback<DynamicPwdLoginResult>() {
            @Override
            public void onSuccess(DynamicPwdLoginResult dynamicPwdLoginResult) {
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_LOGIN_SUCCESS_PAGE, "");
                if (mFromPersonLogin) {
                    APIProxy.navi().navigateTo(UserCenterPage.class, null);
                } else {
                    showLoadingDialog(false);
                    checkUserInfo(null);
                }

            }

            @Override
            public void onFailure(DynamicPwdLoginResult dynamicPwdLoginResult) {
                showLoadingDialog(false);
                if (dynamicPwdLoginResult != null) {
                    ToastForCarpool.show(mActivity, dynamicPwdLoginResult.getResultMsg());
                } else {
                    ToastForCarpool.show(mActivity, "登陆失败");
                }
            }

            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }
        };
        DefaultComRequestFactory factory = new DefaultComRequestFactory();
        ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_INVOKE);
        ComBaseParams params = new ComBaseParams();
        params.setTargetParameter("invoke_dynic_pwd_login_new");
        params.putBaseParameter("phone_num", phone);
        params.putBaseParameter("password", code);
        params.putBaseParameter("callback", callback);
        params.putBaseParameter("loginsourcetype", "pinche");
        request.setParams(params);
        try {
            ComponentManager.getComponentManager().invoke(request);
        } catch (ComException e) {
            e.printStackTrace();
        }
    }

    private void handleBackwardArguments(Bundle bundle) {
        if (bundle != null) {
            if (bundle.containsKey(TextInputSugPage.KEY_PARAM_TYPE)
                    && bundle.containsKey(TextInputSugPage.KEY_PARAM_SUG)) {
                int type = bundle.getInt(
                        TextInputSugPage.KEY_PARAM_TYPE, TextInputSugPage.TYPE_FROM_WHERE);
                TextinputHistroyAndSugListView.TextInputSug sug = (TextinputHistroyAndSugListView.TextInputSug) bundle
                        .getSerializable(TextInputSugPage.KEY_PARAM_SUG);
                if (sug != null) {
                    if (type == TextInputSugPage.TYPE_FROM_WHERE) {
                        if (!sug.getName().equals(mStartPosition.name)) {
                            mStartPosition.name = sug.getName();
                            mStartPosition.address = sug.getAddress();
                            if (mStartPosition == null) {
                            } else {
                                mStartPosition.x = sug.getPoint().getDoubleX();
                                mStartPosition.y = sug.getPoint().getDoubleY();
                            }
                        }
                    } else {
                        if (!sug.getName().equals(mEndPosition.name)) {
                            mEndPosition.name = sug.getName();
                            mEndPosition.address = sug.getAddress();
                            if (mEndPosition == null) {
                            } else {
                                mEndPosition.x = sug.getPoint().getDoubleX();
                                mEndPosition.y = sug.getPoint().getDoubleY();
                            }
                        }
                    }
                }
            }
        }

    }

    private void exchangeFromAndToPosition() {
        if ((!TextUtils.isEmpty(mTextStartName.getText()) && mStartPosition != null) || (!TextUtils.isEmpty(mTextEndName
                .getText()) && mEndPosition != null)) {
            CarpoolPosition temp = new CarpoolPosition();
            temp = mStartPosition;
            mStartPosition = mEndPosition;
            mEndPosition = temp;
            setStartPointAndEndPointText();
        } else {
            if (mTextStartName.getHint().equals("请输入小区名称")) {
                mTextStartName.setHint("请输入公司大厦");
                mTextEndName.setHint("请输入小区名称");
            } else {
                mTextStartName.setHint("请输入小区名称");
                mTextEndName.setHint("请输入公司大厦");
            }

        }

    }

    private void saveLastHomeAndCompany() {
        try {
            CarpoolSharedPreferences.setLatestStartPlaceInfo(mActivity, mStartPosition);
            CarpoolSharedPreferences.setLatestEndPlaceInfo(mActivity, mEndPosition);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void inputMessageComplete(InstructionsForUserDialog.UserinputInfo userinputInfo) {
        StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_LOGIN_SUCCESS_PAGE, "");
        checkUserInfo(userinputInfo);
    }

    /**
     * 校验create接口
     *
     * @param errNo
     * @param reason
     *
     * @return
     */
    private boolean checkErrorNo(int errNo, String reason) {
        boolean isErrNo = false;
        if (errNo >= 90000 && errNo < 100000) {
            ToastForCarpool.show(mActivity, reason);
            isErrNo = true;
        } else if (errNo == 1000 || errNo == 1002 || errNo == 1011) {
            ToastForCarpool.show(mActivity, "网络异常，请稍候再试");
            isErrNo = true;
        } else if (errNo == 1003) {
            ToastForCarpool.show(mActivity, "未登录");
            isErrNo = true;
        } else if (errNo == 1013) {
            ToastForCarpool.show(mActivity, "姓氏超过最大长度");
            isErrNo = true;
        } else if (errNo == 1014) {
            ToastForCarpool.show(mActivity, "性别错误");
            isErrNo = true;
        } else {
            isErrNo = false;
        }
        return isErrNo;

    }

    private void checkUserInfo(InstructionsForUserDialog.UserinputInfo userinputInfo) {
        if (!checkNetworkStatus(true)) {
            showLoadingDialog(false);
            return;
        }
        LocalePlaceInfo startPlaceInfo = new LocalePlaceInfo();
        startPlaceInfo.placeName = mStartPosition.name;
        GeoPoint start = new GeoPoint(mStartPosition.y, mStartPosition.x);
        GeoPoint end = new GeoPoint(mEndPosition.y, mEndPosition.x);

        startPlaceInfo.placeGeo = MapUtils.mc2ll(start);

        LocalePlaceInfo arrivePlaceInfo = new LocalePlaceInfo();
        arrivePlaceInfo.placeName = mEndPosition.name;
        arrivePlaceInfo.placeGeo = MapUtils.mc2ll(end);

        OrderCreateData orderCreateData = new OrderCreateData(mActivity);
        orderCreateData.setStartPlaceInfo(startPlaceInfo);
        orderCreateData.setArrivePlaceInfo(arrivePlaceInfo);
        Long startTimeMillis = mCalendarSelected.getTimeInMillis();
        long startTimeSecs = startTimeMillis / 1000;
        orderCreateData.setStartTime(startTimeSecs + "");
        orderCreateData.setBduss(UserInfoSetting.getBduss());
        String selectCartype = "";
        for (int k = 0; k < carOnclickList.size(); k++) {
            if (k != carOnclickList.size() - 1) {
                selectCartype += carOnclickList.get(k).type + ",";
            } else {
                selectCartype += carOnclickList.get(k).type;
            }

        }
        orderCreateData.setSelectCarType(selectCartype);

        if (userinputInfo != null) {
            orderCreateData.setNickName(userinputInfo.name);
            orderCreateData.setSex(userinputInfo.sex);
        }

        orderCreateData.post(new IDataStatusChangedListener<OrderCreateResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderCreateResponse> comNetData,
                                            OrderCreateResponse orderCreateResponse,
                                            int i) {
                if (orderCreateResponse != null) {
                    if (checkErrorNo(orderCreateResponse.getErrorNo(), orderCreateResponse.getErrorMsg())) {
                        showLoadingDialog(false);
                        isloading = false;
                        return;
                    } else {
                        if (orderCreateResponse.data != null && orderCreateResponse.getErrorNo
                                () == 0) {
                            if (orderCreateResponse.data.userInfo != null) {
                                String name = orderCreateResponse.data.userInfo.nickname;
                                String phone = orderCreateResponse.data.userInfo.mobile;
                                int sex = orderCreateResponse.data.userInfo.gender;
                                showLoadingDialog(false);
                                if (TextUtils.isEmpty(phone)) {
                                    StatisticsUtil.getInstance()
                                            .addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_LOGIN_PAGE, "");
                                    UserCenter.bindPhone();
                                    StatisticsUtil.getInstance()
                                            .addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_LOGIN_SUCCESS_PAGE, "");
                                    isloading = false;
                                    return;
                                } else if (TextUtils.isEmpty(name) || sex == 0) {
                                    StatisticsUtil.getInstance()
                                            .addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_LOGIN_PAGE, "");
                                    mInstructionsForUserDialog.show();
                                } else {
                                    //TODO 创建成功，进去派单页
                                    saveLastHomeAndCompany();
                                    if (orderCreateResponse.data.orderInfo != null) {
                                        String orderId = orderCreateResponse.data.orderInfo.orderId;
                                        showReceiptDialog(orderId, -1);
                                    }
                                }

                            }
                            isloading = false;

                        } else {
                            isloading = false;
                            ToastForCarpool.show(mActivity, "网络异常，请稍候再试");
                            showLoadingDialog(false);
                        }
                    }

                } else {
                    isloading = false;
                    ToastForCarpool.show(mActivity, "网络异常，请稍候再试");
                    showLoadingDialog(false);
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_view:
                if (Config.MONKEY_OPEN) {
                    return;
                }
                goBack();
                break;
            case R.id.right_img:
                //TODO 进入个人中心
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_MAIN_PAGE,
                        StatisticsUtil.OFFLINE_ACT_USER_CENTER_BT);
                if (!UserInfoSetting.isLogin()) {
                    mFromPersonLogin = true;
                    showLoadingDialog(false);
                    showLoginDialog(R.string.carpool_login_title_driver);
                    return;
                }
                APIProxy.navi().navigateTo(UserCenterPage.class, null);

                break;
            case R.id.right_view:
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_MAIN_PAGE,
                        StatisticsUtil.OFFLINE_ACT_USER_CENTER_BT);
                if (!UserInfoSetting.isLogin()) {
                    mFromPersonLogin = true;
                    showLoadingDialog(false);
                    showLoginDialog(R.string.carpool_login_title_driver);
                    return;
                }
                APIProxy.navi().navigateTo(UserCenterPage.class, null);
                //TODO 进入个人中心
                break;
            case R.id.tv_start:
                //TODO 出发地
                Bundle bundleFrom = new Bundle();
                bundleFrom.putInt(
                        TextInputSugPage.KEY_PARAM_TYPE, TextInputSugPage.TYPE_FROM_WHERE);
                bundleFrom.putString(TextInputSugPage.KEY_PARAM_NAME, mStartPosition.name);
                bundleFrom.putSerializable(TextInputSugPage.KEY_PARAM_MYPOSITION, mTempStartPosition);
                APIProxy.navi().navigateTo(TextInputSugPage.class, bundleFrom);
                break;
            case R.id.tv_to:
                //TODO 目的地
                Bundle bundleTo = new Bundle();
                bundleTo.putInt(
                        TextInputSugPage.KEY_PARAM_TYPE, TextInputSugPage.TYPE_GO_WHERE);
                bundleTo.putString(TextInputSugPage.KEY_PARAM_NAME, mEndPosition.name);
                bundleTo.putSerializable(TextInputSugPage.KEY_PARAM_MYPOSITION, mTempStartPosition);
                APIProxy.navi().navigateTo(TextInputSugPage.class, bundleTo);
                break;
            case R.id.lin_time:
                //TODO 时间

                new CarDateTimeDialog(getActivity(), this, this, R.style
                        .TaxiTimeDialog, true,
                        true, true, dateLimit).show();
                break;

            case R.id.iv_exchange:
                //TODO 交换出发地目的地
                exchangeFromAndToPosition();
                break;
            case R.id.appointment_lin:
                //TODO 预约
                if (isloading) {
                    return;
                }
                isloading = true;
                showLoadingDialog(true);
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_MAIN_PAGE,
                        StatisticsUtil.OFFLINE_ACT_CREATE_ORDER_BT);
                if (TextUtils.isEmpty(mTextStartName.getText()) || TextUtils.isEmpty(mTextEndName.getText())) {
                    showLoadingDialog(false);
                    ToastForCarpool.show(mActivity, "出发地或目的地为空");
                    isloading = false;
                    return;
                }
                if (carOnclickList.size() <= 0) {
                    showLoadingDialog(false);
                    ToastForCarpool.show(mActivity, "请选择车型");
                    isloading = false;
                    return;
                }
                if (!UserInfoSetting.isLogin()) {
                    mFromPersonLogin = false;
                    showLoadingDialog(false);
                    showLoginDialog(R.string.carpool_login_title_driver);
                    isloading = false;
                    return;
                } else {
                    checkUserInfo(null);
                }
                break;
            case R.id.tv_refresh:
                requestPrice();
                break;

        }

    }

    /**
     * 等待接单
     */
    private void showReceiptDialog(String orderId, int flag) {
        CarPoolReceiptDialog carPoolReceiptDialog = null;
        if (flag == -1) {
            carPoolReceiptDialog = new CarPoolReceiptDialog(mActivity, orderId);
        } else {
            carPoolReceiptDialog = new CarPoolReceiptDialog(mActivity, orderId, flag);
        }

        carPoolReceiptDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (UserInfoSetting.isLogin()) {
                    requestBaseInfo();
                }
            }
        });
        carPoolReceiptDialog.show();
    }
}
